<template>
  <div class="community">
    <van-swipe :autoplay="3000" class="my-swipe">
      <van-swipe-item
        v-for="(image, index) in images"
        :key="index"
        style="height: 230px"
      >
        <img v-lazy="image" style="width: 100%; height: 240px" />
      </van-swipe-item>
    </van-swipe>
    <Sort
      @refreshCategory="refreshCategory"
      @refreshOrdering="refreshOrdering"
    ></Sort>
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="initArticles"
      :immediate-check="false"
    >
      <Article
        v-for="article in articles"
        :key="'c' + article.id"
        :article="article"
      >
      </Article>
    </van-list>
    <van-button
      icon="plus"
      type="primary"
      class="new-article"
      round
      color="#4497da"
      to="/article/pub"
    />
  </div>
</template>

<script>
import Article from "@/components/Community/Article";
import Sort from "@/components/Community/Sort";
import { getArticlesAPI } from "@/api/articleApi";
export default {
  data() {
    return {
      articles: [],
      loading: false,
      finished: false,
      images: [
        "https://img01.yzcdn.cn/vant/apple-1.jpg",
        "https://img01.yzcdn.cn/vant/apple-2.jpg",
      ],
      params: {
        category: "",
        ordering: "",
        page: 1,
      },
    };
  },
  methods: {
    refreshCategory(value) {
      this.params.category = value;
      this.params.page = 1;
      this.articles = [];
      this.finished = false;
      this.initArticles();
    },
    refreshOrdering(value) {
      this.params.ordering = value;
      this.params.page = 1;
      this.articles = [];
      this.finished = false;
      this.initArticles();
    },
    async initArticles() {
      const { data: res } = await getArticlesAPI(this.params);
      if (res.results) {
        this.articles = [...this.articles, ...res.results];
        this.params.page++;
      }
      this.loading = false;
      if (res.next == null) {
        this.finished = true;
      }
    },
  },
  created() {
    this.initArticles();
  },
  components: {
    Article,
    Sort,
  },
};
</script>

<style lang="less">
.community {
  padding-bottom: 50px;
}

.community .new-article {
  position: fixed;
  right: 10px;
  bottom: 75px;
  z-index: 999;
  width: 40px;
  height: 40px;
  opacity: 0.9;
}
</style>
